package org.example.projectdemo.service;

import org.example.projectdemo.model.entity.Student;
import org.example.projectdemo.repository.AttendanceRepository;
import org.example.projectdemo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * ClassName: StudentService
 * Package: org.example.projectdemo.service.impl
 * Description:
 *
 * @Author ZY
 * @Create 23:09
 * @Version 1.0
 */
@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;
    
    @Autowired
    private AttendanceRepository attendanceRepository;

    // 创建学生
    public Student createStudent(Student student) {
        // 确保ID为null以创建新记录
        student.setId(null);
        // 确保是新记录，未被删除
        student.setDeleted(false);
        student.setDeletedAt(null);
        return studentRepository.save(student);
    }

    // 更新学生
    public Student updateStudent(Student student) {
        // 确保ID存在以更新记录
        if (student.getId() == null || !studentRepository.existsById(student.getId())) {
            throw new IllegalArgumentException("学生ID不存在，无法更新");
        }
        return studentRepository.save(student);
    }

    // 根据ID查找学生（仅查找未删除的）
    public Optional<Student> getStudentById(Long id) {
        return studentRepository.findByIdAndDeletedFalse(id);
    }

    // 检查学生是否存在
    public boolean existsStudentById(Long id) {
        return studentRepository.existsById(id);
    }

    // 查找所有学生（仅查找未删除的）
    public List<Student> getAllStudents() {
        return studentRepository.findByDeletedFalse();
    }

    // 根据学号查找学生（仅查找未删除的）
    public Optional<Student> getStudentByNumber(String studentNumber) {
        return studentRepository.findByStudentNumberAndDeletedFalse(studentNumber);
    }

    // 根据班级查找学生（仅查找未删除的）
    public List<Student> getStudentsByClass(String className) {
        return studentRepository.findByClassNameAndDeletedFalse(className);
    }

    // 根据状态查找学生（如在读、离校）（仅查找未删除的）
    public List<Student> getStudentsByState(Byte state) {
        return studentRepository.findByStateAndDeletedFalse(state);
    }

    // 软删除学生
    public void deleteStudent(Long id) {
        Optional<Student> studentOptional = studentRepository.findById(id);
        if (studentOptional.isPresent()) {
            Student student = studentOptional.get();
            student.setDeleted(true);
            student.setDeletedAt(LocalDateTime.now());
            studentRepository.save(student);
        }
    }
    
    // 永久删除学生（连同考勤记录一起删除）
    @Transactional
    public void permanentDeleteStudent(Long id) {
        // 先删除与该学生关联的所有考勤记录
        attendanceRepository.deleteByStudentId(id);
        // 再删除学生
        studentRepository.deleteById(id);
    }
    
    // 恢复已删除的学生
    public void restoreStudent(Long id) {
        Optional<Student> studentOptional = studentRepository.findById(id);
        if (studentOptional.isPresent()) {
            Student student = studentOptional.get();
            student.setDeleted(false);
            student.setDeletedAt(null);
            studentRepository.save(student);
        }
    }
    
    // 检查学生是否可以被删除（是否有考勤记录）
    public boolean canDeleteStudent(Long id) {
        return !attendanceRepository.existsByStudentId(id);
    }
}